package com.springboot.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

/**
 * @description:
 * @author: zyj
 * @create: 2020-08-06 14:23
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        this.setFieldValByName("gmtCreate",  date, metaObject);
        this.setFieldValByName("gmtModified", date, metaObject);
        this.setFieldValByName("createTime",  date, metaObject);
        this.setFieldValByName("updateTime", date, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("gmtModified", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    public static Date coverLocalDate(LocalDate localDate){
        if (localDate == null) {return null;}

        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
}
